import {
  Breadcrumb,
  Button,
  Card,
  Form,
  Input,
  message,
  Modal,
  Radio,
  Space,
  Upload,
} from 'antd';
import Channel from 'components/Channel';
// import { Component } from 'react';
import { Link } from 'react-router-dom';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import Styles from './index.module.scss';
import { baseURL } from 'utils/request';
import { useEffect, useRef, useState } from 'react';
import { getToken } from 'utils/storage';
import { UploadOutlined } from '@ant-design/icons';
import {
  editArticleByIdAPI,
  getArticleByIdAPI,
  publishArticlesAPI,
} from 'api/articles';
import { useHistory } from 'react-router-dom';
import { useParams } from 'react-router-dom';

export default function ArticlePublish(_props) {
  // 获取id
  const params = useParams();
  // console.log('params  ---  ', params);
  const { id } = params;
  // console.log('id  ---  ', id);
  const [imgUrl, setImgUrl] = useState('');
  const [fileList, setFileList] = useState([]);
  const [type, setType] = useState(1);
  const history = useHistory();
  const draftRef = useRef(false);
  const formRef = useRef(null);
  const props = {
    // name代表后台接收的文件类型
    name: 'image',
    //点击上传图片时弹窗的默认格式 降低用户上传错误的可能
    accept: '.jpg,.png,.jpeg',
    // action代表上传文件的接口地址
    action: `${baseURL}/v1_0/upload`,
    // 设置tokens
    headers: {
      authorization: `Bearer${getToken()}`,
    },
    onChange(info) {
      // if (info.file.status !== 'uploading') {
      //   console.log(info.file, info.fileList);
      // }
      // console.log('info  ---  ', info);
      setFileList(info.fileList);
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
    // 图片点击预览触发的回调
    onPreview(file) {
      // console.log('file  ---  ', file);
      // 回显回来的数据没有thumbUrl，只有url  所以需要做判断
      setImgUrl(file.url || file.thumbUrl);
    },
    // 上传前的回调
    beforeUpload(file) {
      // console.log('file  ---  ', file);
      const whiteList = ['image/jpeg', 'image/jpg', 'image/png'];
      if (!whiteList.includes(file.type)) {
        // console.log('不存在  ---  ');
        // 提示用户
        message.warning('不支持的上传格式');
        // 阻止上传 并且不显示
        return Upload.LIST_IGNORE;
      }
    },
  };
  // 封装获取文章详情异步请求
  const loadArticleById = async (id) => {
    const res = await getArticleByIdAPI(id);
    // console.log('res  ---  ', res);
    // console.log('formRef  ---  ', formRef);
    const type = res.data.cover.type;
    formRef.current.setFieldsValue({ ...res.data, type: type });
    setType(type);
    // fileList是对象格式 所以需要转成对象格式 不然无法识别
    setFileList(res.data.cover.images.map((item) => ({ url: item })));
  };
  useEffect(() => {
    // 判断是否有id  有才发送文章详情请求
    if (id) {
      loadArticleById(id);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  // 字段更新时触发的回调
  const handleValueChange = (changedValues, allValues) => {
    // console.log('changedValues  ---  ', changedValues);
    if (changedValues.type !== undefined) {
      setType(changedValues.type);
    }
  };
  // 计算属性
  // eslint-disable-next-line array-callback-return
  const showList = fileList.filter((item, index) => {
    // 无图
    if (type === 0) return false;
    // 单图
    if (type === 1) return index === 0;
    // 三图
    if (type === 3) return true;
  });
  // 提交
  const handleSubmit = async (value) => {
    // console.log('value  ---  ', value);
    const formData = { ...value };
    formData.cover = {
      type: type,
      images:
        type === 0
          ? []
          : showList.map((item) => item.url || item.response.data.url),
    };
    delete formData.type;
    // 判断图片数量是否正确
    if (fileList.length < type) {
      message.warning('图片数量不对');
      return;
    }
    // 判断id  有则是编辑 没有就是发布
    if (id) {
      // 编辑
      // 发送编辑文章请求
      await editArticleByIdAPI({ id, ...formData }, draftRef.current);
      // 提示用户
      message.success('编辑成功');
    } else {
      // 发布
      // 发送发表文章请求
      await publishArticlesAPI(formData, draftRef.current);
      // 提示用户
      message.success('发布成功');
    }
    // 跳转路由
    history.push('/list');
  };
  return (
    <div style={{ paddingTop: 24 }} className={Styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{id ? '文章编辑' : '文章发布'}</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        {/* 表单区域 */}
        <Form
          ref={formRef}
          size="large"
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          autoComplete="off"
          onFinish={handleSubmit}
          // 富文本设置name属性要配合初始值 不然要报错
          initialValues={{
            content: '',
            channel_id: 0,
            type: 1,
          }}
          // 字段值更新时触发回调事件
          onValuesChange={handleValueChange}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '文章标题不能为空！' }]}
          >
            <Input placeholder="请输入文章标题" />
          </Form.Item>

          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '频道不能为空！' }]}
          >
            <Channel style={{ width: 200 }}></Channel>
          </Form.Item>

          <Form.Item
            label="内容"
            name="content"
            rules={[
              { required: true, message: '文章内容不能为空！' },
              {
                validator: (_, value) => {
                  if (value === '<p><br></p>') {
                    return Promise.reject(new Error('内容不能为空'));
                  }
                  return Promise.resolve();
                },
                message: '文章内容不能为空',
              },
            ]}
          >
            <ReactQuill
              theme="snow"
              placeholder="请输入文章内容..."
            ></ReactQuill>
          </Form.Item>

          <Form.Item label="封面" name="type">
            <Radio.Group>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Upload {...props} listType="picture-card" fileList={showList}>
              {fileList.length < type && (
                <Button icon={<UploadOutlined />}></Button>
              )}
            </Upload>
            <Modal
              title="图片预览"
              visible={!!imgUrl}
              onCancel={() => setImgUrl('')}
              footer={null}
            >
              <img width={400} src={imgUrl} alt="" />
            </Modal>
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 4,
            }}
          >
            <Space>
              <Button type="primary" htmlType="submit">
                {id ? '编辑文章' : '发布文章'}
              </Button>
              <Button
                type="primary"
                htmlType="submit"
                onClick={() => (draftRef.current = true)}
              >
                存草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}
